/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.worldscale.xp.wslib.im.jabber.impl;

import java.util.Stack;


import net.worldscale.xp.wslib.im.jabber.JabberClient;
import net.worldscale.xp.wslib.wsxml.WsXML;
import net.worldscale.xp.wslib.wsxml.sax.IAttributes;
import net.worldscale.xp.wslib.wsxml.sax.SaxException;
import net.worldscale.xp.wslib.wsxml.sax.SaxHandler;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;

/**
 *
 * @author Kun
 */
final class ImplJabberReceiver extends SaxHandler {

    public ImplJabberReceiver(JabberClient.StreamListener sl) {
        mListener = sl;
        mElementStack = new Stack<Element>();
        mDoc = WsXML.getInstance().getDOMImplementation().createDocument(null, null, null);
    }
    private final Stack<Element> mElementStack;
    private final Document mDoc;
    private final JabberClient.StreamListener mListener;

    @Override
    public void startElement(String uri, String localName, String qName, IAttributes attributes) throws SaxException {
        final Element ele = mDoc.createElement(qName);
        final int len = attributes.getLength();
        for (int i = 0; i < len; i++) {
            ele.setAttribute(attributes.getQName(i), attributes.getValue(i));
        }
        if (this.mElementStack.isEmpty()) {
            this.mListener.onStreamOpen();
        }
        this.mElementStack.push(ele);
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SaxException {
        final Element child, parent;
        child = this.mElementStack.pop();
        if (this.mElementStack.isEmpty()) {
            this.mListener.onStreamClose();
            return;
        } else {
            parent = this.mElementStack.peek();
        }
        if (parent.getTagName().equals("stream:stream")) {
            this.mListener.onStanza(child);
        } else {
            parent.appendChild(child);
        }
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SaxException {
        final Text txt = mDoc.createTextNode(new String(ch, start, length));
        this.mElementStack.peek().appendChild(txt);
    }

    @Override
    public void startDocument() throws SaxException {
        this.mElementStack.removeAllElements();
    }

    @Override
    public void endDocument() throws SaxException {
        this.mElementStack.removeAllElements();
    }
}
